<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Grid;
use App\Models\GridImg;
use App\Models\Village;
use App\Models\Villager;
use App\Models\ExcelSet;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use App\Services\ImportService;
use App\Services\ExportService;
use Maatwebsite\Excel\Facades\Excel;

// 导入导出
class ExcelController extends Controller
{
    //导入文件
    public function load(Request $request)
    {
       // 验证
       $validate = Validator::make($request->all(), [
            'type' => 'required|in:1',
            'street_id' => 'required',
            'village_id' => 'required',
            'project_id' => 'required',
            'segment_id' => 'required',
            'grid_group_id' => 'required',
            'if_repeat' => 'required',
        ], [
            'type.required' => '请输入导入类型',
            'type.in' => '请输入正确的导入类型',
            'street_id.required' => '请输入街道',
            'village_id.required' => '请输入村庄',
            'project_id.required' => '请输入项目',
            'segment_id.required' => '请输入号段',
            'grid_group_id.required' => '请输入网格组',
            'if_repeat.required' => '请输入是否允许重复',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $request->all();

        $file = $request->file('file');
        $import = new ImportService($params);
        Excel::import($import,$file);
        
        return $import->result;   
    }

    //导出文件
    public function export(Request $request)
    {
        // 验证
        $validate = Validator::make($request->all(), [
            'type' => 'required',
            'excel_type' => 'required',
        ], [
            'type.required' => '请输入类型',
            'excel_type.required' => '请输入导出类型',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }
       
        $params = $request->all();

        $sign_time = $request->input('sign_time', ''); // 签约时间
        $vacate_room_time = $request->input('vacate_room_time', ''); // 腾房时间

        $ExcelSet = ExcelSet::query()->where('id',$params['excel_type'])->first();
       
        if(!$ExcelSet){
            return showError('未查询到此导出类型');
        }
        $content=$ExcelSet['content'];
        $content=json_decode($content,true);

        $text =array_column($content,'text');
        $value =array_column($content,'value');

        $data=$this->getSignData($value,$sign_time,$vacate_room_time);
        if (isset($data['code']) && $data['code'] == 0) {
            return $data;
        }

        if($params['type']==1){
            return showData($data);
        }

        $export = new ExportService($text, $data);
        return Excel::download($export, $ExcelSet['name'].'.xlsx',);
    }


    // 获取签约数据
    public function getSignData($value,$sign_time,$vacate_room_time){
        try{
            $grid = Grid::query()
            ->when($sign_time, function ($query) use ($sign_time) {
                $sign_time=explode(',',$sign_time);
                $query->where('sign_time', '>=', $sign_time[0])->where('sign_time', '<=', $sign_time[1]);
            })
            ->when($vacate_room_time, function ($query) use ($vacate_room_time) {
                $vacate_room_time=explode(',',$vacate_room_time);
                $query->whereHas('grid_img_2', function($query) use ($vacate_room_time){
                    $query->where('type', 6)->where('created_at', '>=', $vacate_room_time[0])->where('created_at', '<=', $vacate_room_time[1]);
                });
            })
            ->with(['grid_img_2'=> function ($query) {
                $query->where('type', 6);
            }])
            ->with('grid_group:id,name')
            ->with('villager:grid_id,name,identity_card,phone')
            ->with('agent:grid_id,name,identity_card,phone')
            ->with('grid_area_arr')
            ->with(['grid_house' => function ($query) {
                $query->where('type',1)->with('house_type:id,name,area');
            }])
            ->with(['grid_price'=> function ($query) {
                $query->where('type', 0);
            }])
            ->where('if_sign',1)
            ->where('project_id',auth('admin')->user()->project_id)
            ->orderBy('sign_time')
            ->get()
            ->toArray();

            $data=[];
            if($grid){
                foreach($grid as $k=>$v){
                    $sign_time=$v['sign_time'];//
                    $sign_num=$v['sign_num'];//
                    $grid_group_name=$v['grid_group']['name'];//
                    $grid_name=$v['name'];//
        // 村民代理人
                    $villager_name=implode(',',array_column($v['villager'],'name'));//
                    $villager_identity_card="'".implode(',',array_column($v['villager'],'identity_card'));//
                    $villager_phone=implode(',',array_column($v['villager'],'phone'));//
                    $agent_name=$v['agent']['name']??'/';//
                    $agent_identity_card=isset($v['agent']['identity_card'])?"'".$v['agent']['identity_card']:'/';//
                    $agent_phone=$v['agent']['phone']??'/';//
        //    面积     
                    if(count($v['grid_area_arr'])==2){
                        if($v['grid_area_arr'][0]['type']==1){
                            $grid_area_arr=$v['grid_area_arr'][1];
                        }else{
                            $grid_area_arr=$v['grid_area_arr'][0];
                        }
                    }else{
                        $grid_area_arr=$v['grid_area_arr'][0];
                    }
                    $use_area=$grid_area_arr['use_area'];//
                    $build_area=$grid_area_arr['build_area'];//
                    $two_area=$grid_area_arr['two_area'];//
                    $yard_area=$grid_area_arr['yard_area'];//
                    $dualuse_area=$grid_area_arr['dualuse_area'];//
                    $business_award_time=$v['business_award_time'];//
                    $reward_area=$grid_area_arr['reward_area'];//
                    $improve_area=$grid_area_arr['improve_area'];//
                    $supply_area=$grid_area_arr['supply_area'];//
        // 户型
                    $house_name_str='';
                    $house_area_str=0;
                    foreach($v['grid_house'] as $v1){
                        $house_name_str.=$v1['house_type']['area'].',';
                        $house_area_str+=$v1['house_type']['area'];
                    }
                    $count_house=count($v['grid_house']);//
                    $house_name_str=$house_name_str;//
                    $house_area_str=$house_area_str;//
        // 费用
                    $if_decorate_fee=$v['grid_price']['if_decorate_fee'];//
                    $subsidy_fee=$v['grid_price']['subsidy_fee'];//
                    $transition_fee=$v['grid_price']['transition_fee'];//
                    $other_subsidy_fee=$v['grid_price']['other_subsidy_fee'];//
                    $stop_fee=$v['grid_price']['stop_fee'];//
                    $require_sign_fee=$v['grid_price']['require_sign_fee'];//
                    $require_clear_fee=$v['grid_price']['require_clear_fee'];//
                    $supply_total_fee=$v['grid_price']['supply_total_fee'];//
                    $house_difference=$v['grid_price']['house_difference_fee']>0?'下靠':'上靠';//
                    $house_difference_area=round($grid_area_arr['supply_area']-$house_area_str,2);//
                    $house_difference_fee=$v['grid_price']['house_difference_fee'];//
                    $party_a_fee=$v['grid_price']['party_a_fee'];//
                    $party_b_fee=$v['grid_price']['party_b_fee'];//
                    $vacate_room_time=isset($v['grid_img_2']['created_at'])?date('Y-m-d',strtotime($v['grid_img_2']['created_at'])):'';//
                    
                    foreach($value as $v2){
                        $data[$k][$v2]=$$v2;
                    }
                }
            }
        
            return collect($data);
        } catch (\Exception $e) {
            return showError('参数错误');
        }
    }

}
